package com.wwj.controller.user;


import com.wwj.common.constant.JwtClaimsConstant;
import com.wwj.common.properties.JwtProperties;
import com.wwj.common.result.Result;
import com.wwj.common.utils.JwtUtil;
import com.wwj.pojo.dto.EmployeeLoginDTO;
import com.wwj.pojo.dto.UserLoginDTO;
import com.wwj.pojo.entity.Employee;
import com.wwj.pojo.entity.User;
import com.wwj.pojo.vo.EmployeeLoginVO;
import com.wwj.pojo.vo.UserLoginVO;
import com.wwj.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags="用户端相关接口")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private JwtProperties jwtProperties;

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result register(@RequestBody User user){
        userService.register(user);
        return Result.success();
    }


    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}",userLoginDTO);

        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        log.info("token：{}",token);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @GetMapping("/{userName}")
    @ApiOperation(value = "个人中心查询")
    @Cacheable(cacheNames = "UserCenter",key = "#userName")
    public Result<User> UserCenter(@PathVariable String userName){
        User user=userService.UserCenter(userName);
        return Result.success(user);
    }

    @PutMapping
    @ApiOperation(value = "修改用户")
    @CacheEvict(cacheNames = "UserCenter",allEntries = true)
    public Result<User> updateUser(@RequestBody User user){
        User user1 = userService.updateUser(user);
        return Result.success(user1);
    }
}
